package com.kbxwn.logmanager.log;

import com.kbxwn.logmanager.entity.EventMessage;
import com.kbxwn.logmanager.entity.LogEntity;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * <p>描述：
 * <p>作者：liangguokui 2018/3/19
 */
public class LogManager {

    public static final String FONT_END = "</font>";
    public static final String HTML_COLOR_TIME = "<font color='#ffffff'>";

    // 固定显示1000条log，log太多可能会造成oom
    private LimitQueue<LogEntity> logQueue = new LimitQueue<>(1000);

    private static class InstanceManager {
        private static LogManager logManager = new LogManager();
    }

    public static LogManager intance() {
        return InstanceManager.logManager;
    }


    public LogManager() {
    }

    @Subscribe
    public void receiveLog(String log) {

        LogEntity logEntity = beautifyLog(log);
        logQueue.offer(logEntity);

        EventMessage temp = new EventMessage("show_new_log", logEntity);
        EventBus.getDefault().post(temp);
    }

    private LogEntity beautifyLog(String log) {
        StringBuilder builder = new StringBuilder();

        String loglevel = logLevel(log);
        String logtag = logTag(loglevel, log);
        String htmlColor = logColor(loglevel);

        builder.append(log);
        builder.insert(0, HTML_COLOR_TIME);
        builder.insert(40, FONT_END);

        builder.insert(47, htmlColor);
        builder.append(FONT_END);

        return new LogEntity(loglevel, logtag, builder.toString());
    }

    private String logColor(String loglevel) {
        if ("i".equalsIgnoreCase(loglevel)) {
            return "<font color='#27B239'>";
        } else if ("v".equalsIgnoreCase(loglevel)) {
            return "<font color='#BBBBBB'>";
        } else if ("d".equalsIgnoreCase(loglevel)) {
            return "<font color='#068DBB'>";
        } else if ("w".equalsIgnoreCase(loglevel)) {
            return "<font color='#BBBB23'>";
        } else if ("e".equalsIgnoreCase(loglevel)) {
            return "<font color='#ff0000'>";
        } else {
            return "<font color='#ff0000'>";
        }
    }

    private String logLevel(String log) {
        if (log.length() < 20) {
            return "";
        }

        return log.substring(19, 20);
    }

    private String logTag(String level, String log) {
        int start = log.indexOf(level + "/");
        int end = log.indexOf("(");

        if (start < 0 || end < 0) {
            return "";
        }

        return log.substring(start + 2, end).trim();
    }

    public LimitQueue<LogEntity> getLogQueue() {
        return new LimitQueue<>(logQueue);
    }
}
